/*******************************************************************************
 * Copyright (c) 2008, 2009 Tapestry IDE Developers
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Tapestry IDE Developers - initial API and implementation
 *******************************************************************************/
package com.googlecode.tapestry.ide.core;

import java.util.LinkedHashSet;
import java.util.Set;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

import com.googlecode.tapestry.ide.TapestryPlugin;

/**
 * Some helper methods.
 */
public class TapestryCoreUtils {

	/**
	 * Returns a list of all projects with the Tapestry project nature.
	 * 
	 * @return the tapestry projects
	 */
	public static Set<IProject> getTapestryProjects() {
		Set<IProject> projects = new LinkedHashSet<IProject>();
		for (IProject project : ResourcesPlugin.getWorkspace().getRoot()
				.getProjects()) {
			if (isTapestryProject(project)) {
				projects.add(project);
			}
		}
		return projects;
	}

	/**
	 * Returns true if given resource's project is a Tapestry project.
	 * 
	 * @param resource
	 *            the resource
	 * 
	 * @return true, if checks if is Tapestry project
	 */
	public static boolean isTapestryProject(IResource resource) {
		return hasNature(resource, TapestryPlugin.NATURE_ID);
	}

	/**
	 * Returns true if given resource's project has the given nature.
	 * 
	 * @param resource
	 *            the resource
	 * @param natureId
	 *            the nature id
	 * 
	 * @return true, if checks for nature
	 */
	public static boolean hasNature(IResource resource, String natureId) {
		if (resource != null && resource.isAccessible()) {
			IProject project = resource.getProject();
			if (project != null) {
				try {
					return project.hasNature(natureId);
				} catch (CoreException e) {
					TapestryPlugin.getDefault().getLog().log(
							new Status(IStatus.ERROR, TapestryPlugin.PLUGIN_ID,
									0, "Internal Error", e));
				}
			}
		}
		return false;
	}

	/**
	 * Combine hash codes.
	 * 
	 * @param hashCode1
	 *            the hash code1
	 * @param hashCode2
	 *            the hash code2
	 * 
	 * @return the int
	 */
	public static int combineHashCodes(int hashCode1, int hashCode2) {
		return hashCode1 * 17 + hashCode2;
	}

}
